'use strict';

const BaseController = require('../../core/base_controller');

class BrowseController extends BaseController {
  // 获取浏览历史列表
  async index() {
    const { ctx } = this;
    const { type = 'job', page = 1, pageSize = 10 } = ctx.query;
    const { user_id } = ctx.headers;

    // 构建查询条件
    const where = {
      user_id,
      type
    };

    const { count, rows } = await ctx.model.UserBrowse.findAndCountAll({
      where,
      order: [['created_at', 'DESC']],
      offset: (page - 1) * pageSize,
      limit: parseInt(pageSize),
      include: [{
        model: ctx.model.JobOpening,
        as: 'job',
        attributes: ['id', 'title', 'salary', 'company_name', 'address'],
        where: {
          status: 1,
          del_flag: 0
        },
        required: false
      }]
    });

    // 过滤掉已删除或下架的职位
    const list = rows.filter(item => item.job);

    this.success({
      list,
      pagination: {
        total: count,
        current: parseInt(page),
        pageSize: parseInt(pageSize),
      },
    });
  }

  // 添加浏览记录
  async create() {
    const { ctx } = this;
    const { browse_id, type = 'job' } = ctx.request.body;
    const { user_id } = ctx.headers;

    // 参数验证
    const rules = {
      browse_id: { type: 'integer', required: true },
      type: { 
        type: 'enum', 
        values: ['job'], 
        required: true 
      },
    };

    try {
      ctx.validate(rules);
    } catch (err) {
      ctx.throw(400, '参数错误');
    }

    // 检查浏览对象是否存在
    const target = await ctx.model.JobOpening.findByPk(browse_id);
    if (!target) {
      ctx.throw(404, '浏览对象不存在');
    }

    // 检查是否已有浏览记录
    let browse = await ctx.model.UserBrowse.findOne({
      where: {
        user_id,
        browse_id,
        type
      }
    });

    if (browse) {
      // 如果已有记录，更新时间
      await browse.update({
        updated_at: new Date()
      });
    } else {
      // 创建新记录
      browse = await ctx.model.UserBrowse.create({
        user_id,
        browse_id,
        type
      });
    }

    this.success(browse);
  }

  // 删除浏览记录
  async destroy() {
    const { ctx } = this;
    const { ids } = ctx.request.body; // 支持批量删除
    const { user_id } = ctx.headers;

    if (!Array.isArray(ids) || ids.length === 0) {
      ctx.throw(400, '参数错误');
    }

    await ctx.model.UserBrowse.destroy({
      where: {
        id: ids,
        user_id // 确保只能删除自己的记录
      }
    });

    this.success(null, '删除成功');
  }

  // 清空浏览记录
  async clear() {
    const { ctx } = this;
    const { type = 'job' } = ctx.request.body;
    const { user_id } = ctx.headers;

    await ctx.model.UserBrowse.destroy({
      where: {
        user_id,
        type
      }
    });

    this.success(null, '清空成功');
  }
}

module.exports = BrowseController; 